export default {
    data() {
        return {
            loading: false,
            search: {},
            list: [],
            page: {
                total: 10,
                page: 1,
                rows: 10,
                time: null,
                lastPage: false,
            },
            api: null
        }
    },
    async mounted() {
        window.addEventListener('scroll', this.handlerBottom)
        // document.querySelector('#app').addEventListener('scroll', this.handlerBottom)
    },
    methods: {
        async getList() {
            this.loading = true
            let page = JSON.parse(JSON.stringify(this.page))
            delete page.time
            let search = JSON.parse(JSON.stringify(this.search))
            for (let i in search) {
                if (!search[i]) {
                    delete search[i]
                }
            }
            let req = {
                ...search,
                ...page
            }
            delete req.total
            try {
                const {data} = await this.api(req)
                console.log(data)
                if (data.list === undefined) {
                    this.list.push(...data.rows)
                    if (!data.rows || data.rows.length < this.page.rows) {
                        this.page.lastPage = true
                        return
                    }
                } else {
                    this.list.push(...data.list)
                    if (!data.list || data.list.length < this.page.rows) {
                        this.page.lastPage = true
                        return
                    }
                }
            } catch (e) {
                console.error(e)
            }
            this.loading = false
        },
        handlerSearch() {
            this.page.page = 1
            this.page.lastPage = false
            this.list = []
            this.getList()
        },
        handlerPageChange() {
            this.page.page += 1
            this.getList()
        },
        // 触底翻页
        handlerBottom(e) {
            clearTimeout(this.page.time)
            this.page.time = setTimeout(() => {
                const {clientHeight, scrollTop, scrollHeight} = document.documentElement
                if ((clientHeight + scrollTop + 5) > scrollHeight) {
                    console.log('到底了')
                    if (this.page.lastPage) {
                        console.log('没有了')
                        return
                    }
                    this.handlerPageChange()
                }
            }, 300)
        }
    },
    beforeDestroy() {
        window.removeEventListener('scroll', this.handlerBottom)
        // document.querySelector('#app').removeEventListener('scroll', this.handlerBottom)
    }
}
